package cn.songtx.iot.config;

import cn.songtx.iot.utils.JWTUtils;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;

public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        // 解决增加拦截器后,跨域注解失效问题
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        // token建议放在请求头中,从请求头Authorization中获取token
        String token = request.getHeader("Authorization");
        HashMap<String, Object> map = new HashMap<>();

        try {
            JWTUtils.verify(token);      // 验证正常返回true
            return true;
        } catch (SignatureVerificationException e) {
            map.put("msg", "签名无效!");
        } catch (TokenExpiredException e) {
            map.put("msg", "token过期!");
        } catch (AlgorithmMismatchException e) {
            map.put("msg", "token算法不一致!");
        } catch (Exception e) {
            map.put("msg", "token无效!");
        }
        map.put("state", false);
        // 将map转化为JSON
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
